package DataAccess;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import pojo.CayThaoLuanPOJO;

public class CayThaoLuanDA extends BaseDA{
	protected CayThaoLuanPOJO getProperties(ResultSet rss) throws SQLException{
		CayThaoLuanPOJO rs=new CayThaoLuanPOJO();
		rs.setId(rss.getInt("ID"));
		rs.setVersion(rss.getTimestamp("version").getTime());
		rs.setNoiDung(rss.getString("NoiDung"));
		rs.setIdNhom(rss.getInt("IDNhom"));
		rs.setIdNguoiTao(rss.getInt("IDNguoiTao"));
		return rs;
	}
	public CayThaoLuanPOJO get(int id){
		CayThaoLuanPOJO rs=null;
		String sql="select * from caythaoluan where id="+id;		
		try{
			
			ResultSet rss=provider.executeQuery(sql);
			if(rss.next()){
				rs=getProperties(rss);				
			}
		}catch(Exception e){
			rs=null;
		}		
		return rs;
	}
	public ArrayList<CayThaoLuanPOJO> getByNhom(int idNhom){
		String sql="select * from caythaoluan where IDNhom="+idNhom;
		ArrayList<CayThaoLuanPOJO> rs=null;
		try{
			rs=new ArrayList<CayThaoLuanPOJO>();
			ResultSet rss=provider.executeQuery(sql);
			while(rss.next()){
				CayThaoLuanPOJO ctl=getProperties(rss);
				rs.add(ctl);
			}
		}catch (Exception e) {
			rs=null;
		}
		return rs;
	}
	//Lấy tất cả cây mà người dùng tham gia dựa vào nhóm của người đó
	public ArrayList<CayThaoLuanPOJO> getByNguoiDung(int idNguoiDung){
		String sql="select distinct cay.* from nhom_nguoidung nhom join caythaoluan cay on nhom.id=cay.idnhom where idnguoidung="+idNguoiDung;
		ArrayList<CayThaoLuanPOJO> rs=null;
		try{
			rs=new ArrayList<CayThaoLuanPOJO>();
			ResultSet rss=provider.executeQuery(sql);
			while(rss.next()){
				CayThaoLuanPOJO ctl=getProperties(rss);
				rs.add(ctl);
			}
		}catch (Exception e) {
			rs=null;
		}
		return rs;
	}
	public int insert(CayThaoLuanPOJO cayThaoLuan) {
		int rs = -1;
		String procName = "spInsertCayThaoLuan";
		String[] input = new String[] { cayThaoLuan.getIdNguoiTao() + "", cayThaoLuan.getNoiDung(),
				cayThaoLuan.getIdNhom() + "" };
		try {
			ResultSet rss = provider.executeStore(procName, input);
			if (rss.next()) {
				rs = rss.getInt("ID");
			}
		} catch (Exception e) {
			rs = -1;
		}
		return rs;
	}
	public void updateVersion(int idCay, long version){
		String sql="update caythaoluan set version=FROM_UNIXTIME("+version+") where id="+idCay;
		provider.executeUpdate(sql);
	}
}
